#include "http.h"

Http::Http(QString url,                                     //需要自己构造?后的字符串
           Http::Method method)                             //只支持异步
    :method(method)
{

    manager = new QNetworkAccessManager();
    request = QNetworkRequest((QUrl(url)));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
}

Http::~Http()
{
    delete manager;
}

void Http::setData(QString &data)
{
    Http::data = data.toUtf8();
}

void Http::setData(QByteArray data)
{
    Http::data = data;
}

void Http::setRequest(QNetworkRequest request)
{
    Http::request = request;
}

QNetworkRequest Http::getRequest()
{
    return request;
}

QNetworkAccessManager *Http::getAccessManager()
{
    return manager;
}

void Http::send()
{
    switch (method) {
    case Http::GET: manager->get(request); break;
    case Http::HEAD: manager->head(request); break;
    case Http::POST: manager->post(request, data); break;
    case Http::PUT: manager->put(request, data); break;
    case Http::DELETE: manager->deleteResource(request); break;
    default:
        break;
    }
}

/**
 * @brief Http::checkHttpResponseError 检查响应数据
 * @param reply 槽函数的响应信号参数
 * @return 返回一个json对象
 */
QJsonObject Http::checkHttpResponseError(QNetworkReply *reply)
{
    QJsonObject jsonObject;
    if(reply->error() != QNetworkReply::NoError)//过滤请求错误
    {
        QMessageBox::critical(nullptr, "Connect Error", reply->errorString());
        qCritical() << reply->errorString();
        return jsonObject;
    }

    //判断响应数据
    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    if(!statusCode.isValid() || statusCode.toInt() != 200)//如果解析响应状态码错误或者状态码!=200
    {
        QVariant reason =  reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute);
        if(reason.isValid())
            QMessageBox::critical(nullptr, "Response Error", reason.toString());
        else
            QMessageBox::critical(nullptr, "Response Error", "响应错误");
        qCritical() << "Response Error" << reason.toString();
        return jsonObject;
    }

    //判断自定义的响应状态码
    //响应成功，解析数据
    QJsonParseError jsonerror;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll(), &jsonerror);
    qDebug() << "response data: " <<
                QString(jsonDoc.toJson(QJsonDocument::JsonFormat::Compact));
    if(jsonDoc.isNull() || jsonerror.error != QJsonParseError::NoError)
    {
        QMessageBox::critical(nullptr, "JsonParseError", jsonerror.errorString());
        qCritical() << jsonerror.errorString() << "json解析失败";
        return jsonObject;
    }
//    QJsonValue msgJsonValue = jsonDoc.object().value("message"); //错误附带的消息
//    QJsonValue codeJsonValue = jsonDoc.object().value("status"); //服务器中定义为code
//    if(codeJsonValue.isUndefined() || codeJsonValue.isNull())//检查code合法性
//    {
//        QMessageBox::critical(nullptr, "JsonValueError", "The 'code' key failed to match.");
//        qCritical() << "JsonValueError: The 'code' key failed to match.";
//        return jsonObject;
//    }
//    int code = (int)codeJsonValue.toInt();
//    QString msg = msgJsonValue.toString();
//    if(code != 200)
//    {
//        QMessageBox::critical(nullptr, "Response error",
//                              QString("code: %1\nmsg: %2").arg(code, 3, 10).arg(msg));
//        qCritical() << "Response error: " <<
//                       QString("code: %1\nmsg: %2").arg(code, 3, 10).arg(msg);
//        return jsonObject;
//    }
    jsonObject = jsonDoc.object();
    return jsonObject;
}

void Http::setRawHeader(const QByteArray &headerName, const QByteArray &headerValue)
{
    request.setRawHeader(headerName, headerValue);
}
